from django.shortcuts import render
from suanfa_s import settings
from PIL import Image, ImageOps
import time
from suanfa_sapp import models
# Create your views here.
import matplotlib.pyplot as plt
import numpy as np
import skimage

from skimage.metrics import peak_signal_noise_ratio
from skimage.metrics import structural_similarity
from skimage.metrics import mean_squared_error
from scipy.ndimage.filters import gaussian_filter as gauss
from scipy.ndimage.filters import median_filter as med
import os
import cv2


def index(request):

    if request.method == 'GET':
        return render(request, 'index.html')
    else:

        msg = ''
        file_obj=request.FILES.get('file')

        # image_db = models.Dback(
        #
        #     image=file_obj
        # )
        # image_db.save()
        print(file_obj)
        if file_obj is None:
            msg = '提示：请选择图片后上传'
            return render(request, 'index.html',{'msg':msg})
        file_obj_str = str(file_obj)
        print('file_obj_str',file_obj_str)

        ti = file_obj_str.split('.')[-1].lower()
        if ti == 'bmp' or ti == 'jpg' or ti == 'jpge' or ti == 'png' or ti == 'gif':
            img_path = 'img/' + file_obj_str
            models.Dback.objects.create(image=file_obj)
            # print('models.Dback.objects.all()', models.Dback.objects.all())
            settings.IMAGE_PATH = img_path

            print("img_path_index", img_path)

            return render(request, 'bak.html',{'path':img_path})
        else:
            msg = '提示：请选择图片类型文件上传'
            return render(request, 'index.html',{'msg':msg})


class ProcessImage:
    def __init__(self, image_path):
        self.image_path = image_path
        self.save_path = image_path.split('.')[:-1]
        self.orig_img = Image.open(self.image_path)

    def save_img(self, need_path):
        save_path = 'suanfa_sapp/static/' + need_path
        plt.savefig(save_path)
        plt.cla()
        plt.close("all")

    def compute_data(self, origin, new):
        # 峰值信噪比
        pnsr = peak_signal_noise_ratio(origin, new, data_range=255)
        # 结构相似性
        ssim = structural_similarity(origin, new, data_range=255, multichannel=True)
        # 均方误差
        mse = mean_squared_error(origin, new)
        return pnsr, ssim, mse

    def dengbisuofang(self):
        '''
        等比缩放
        '''
        print('self.save_path:',self.save_path)
        print('type self.save_path:', type(self.save_path))
        print('self.save_path[0]:',self.save_path[0])

        orig_height, orig_width = self.orig_img.size
        print('Original size:', orig_height, 'x', orig_width)
        target_size = (orig_height/2, orig_width/2)
        scaled_img = self.orig_img.copy()
        scaled_img.thumbnail(target_size, Image.ANTIALIAS)
        scaled_height, scaled_width = scaled_img.size
        print('Scaled size:', scaled_height, 'x', scaled_width)
        # scaled_img.save(save_path)
        new_img = Image.new("RGB", (orig_height, orig_width), (255, 255, 255))

        # 将缩放的图像放置在白色背景上
        new_img.paste(scaled_img, (
            int((target_size[0] - scaled_img.size[0]) / 2), int((target_size[1] - scaled_img.size[1]) / 2)))
        new_height, new_width = new_img.size
        print('New size:', new_height, 'x', new_width)

        # 显示原来的和缩放后的图像
        # Create a figure
        fig = plt.figure(figsize=(16, 16))

        # Subplot for original image
        a = fig.add_subplot(1, 3, 1)
        imgplot = plt.imshow(self.orig_img)
        a.set_title('Original')

        # Subplot for scaled image
        a = fig.add_subplot(1, 3, 2)
        imgplot = plt.imshow(scaled_img)
        a.set_title('Scaled to 1/2')

        # Subplot for resized image
        a = fig.add_subplot(1, 3, 3)
        imgplot = plt.imshow(new_img)
        a.set_title('Resized')

        if not os.path.exists('suanfa_sapp/static/' + "img/" + 'dengbi'):
            os.mkdir('suanfa_sapp/static/' + "img/" + 'dengbi')
        # save_path = 'suanfa_sapp/static/' + self.save_path[0].split('/')[0] + '/dengbi/' + self.save_path[0].split('/')[1] + '_dengbi.jpg'
        need_path = self.save_path[0].split('/')[0] + '/dengbi/' + self.save_path[0].split('/')[1] + '_dengbi.jpg'
        self.save_img(need_path)

        return need_path

    def add_salt_pepper_noise(self, image):
        h, w = image.shape[:2]
        nums = 10000
        rows = np.random.randint(0, h, nums, dtype=np.int)
        cols = np.random.randint(0, w, nums, dtype=np.int)
        for i in range(nums):
            if i % 2 == 1:
                image[rows[i], cols[i]] = (255, 255, 255)
            else:
                image[rows[i], cols[i]] = (0, 0, 0)
        return image

    def salt_pepper_noise(self):
        # 随机噪声
        orig_img = cv2.imread(self.image_path)
        orig_img = cv2.cvtColor(orig_img, cv2.COLOR_BGR2RGB)
        img3 = np.array(orig_img)
        orig_img_salt_pepper_noise = self.add_salt_pepper_noise(orig_img)
        # Create a figure
        fig = plt.figure(figsize=(16, 8))

        # Subplot for original image
        a = fig.add_subplot(1, 2, 1)
        imgplot = plt.imshow(img3)
        a.set_title('Before')

        # Subplot for processed image
        a = fig.add_subplot(1, 2, 2)
        # imgplot = plt.imshow(img3PIL_eq)
        imgplot = plt.imshow(orig_img_salt_pepper_noise)
        a.set_title('After')
        pnsr, ssim, mse = self.compute_data(img3, orig_img_salt_pepper_noise)

        if not os.path.exists('suanfa_sapp/static/' + "img/" + 'salt_pepper_noise'):
            os.mkdir('suanfa_sapp/static/' + "img/" + 'salt_pepper_noise')
        need_path = self.save_path[0].split('/')[0] + '/salt_pepper_noise/' + self.save_path[0].split('/')[1] + '_salt_pepper_noise.jpg'
        self.save_img(need_path)
        return need_path, pnsr, ssim, mse


    # def gradient(self):
    #     '''梯度直方图
    #
    #     '''
    #
    #     img3 = np.array(self.orig_img)
    #     img3PIL_eq = ImageOps.equalize(Image.fromarray(img3))
    #     # Create a figure
    #     fig = plt.figure(figsize=(16, 8))
    #
    #     # Subplot for original image
    #     a = fig.add_subplot(2, 2, 1)
    #     imgplot = plt.imshow(img3)
    #     a.set_title('Before')
    #
    #     # Subplot for processed image
    #     a = fig.add_subplot(2, 2, 2)
    #     # imgplot = plt.imshow(img3PIL_eq)
    #     imgplot = plt.imshow(img3PIL_eq)
    #     a.set_title('After ')
    #
    #     img3_eq = np.array(img3PIL_eq)
    #
    #     a = fig.add_subplot(2, 2, 3)
    #     imgplot = plt.hist(img3.ravel())
    #     a.set_title('Histogram')
    #
    #     a = fig.add_subplot(2, 2, 4)
    #     imgplot = plt.hist(img3_eq.ravel())
    #     a.set_title('After Histogram')
    #
    #     if not os.path.exists('suanfa_sapp/static/' + "img/" + 'gradient'):
    #         os.mkdir('suanfa_sapp/static/' + "img/" + 'gradient')
    #     need_path = self.save_path[0].split('/')[0] + '/gradient/' + self.save_path[0].split('/')[1] + '_gradient.jpg'
    #     self.save_img(need_path)
    #     return need_path

    def random_noise(self):
        # 随机噪声
        orig_img = Image.open(self.image_path)
        img3 = np.array(orig_img)
        # img3PIL_eq = ImageOps.equalize(Image.fromarray(img3))
        # img3_eq = np.array(img3PIL_eq)
        img3_n = skimage.util.random_noise(img3)
        # Create a figure
        fig = plt.figure(figsize=(16, 8))

        # Subplot for original image
        a = fig.add_subplot(1, 2, 1)
        imgplot = plt.imshow(img3)
        a.set_title('Before')

        # Subplot for processed image
        a = fig.add_subplot(1, 2, 2)
        # imgplot = plt.imshow(img3PIL_eq)
        imgplot = plt.imshow(img3_n)
        a.set_title('After')
        pnsr, ssim, mse = self.compute_data(img3, img3_n)
        if not os.path.exists('suanfa_sapp/static/' + "img/" + 'random_noise'):
            os.mkdir('suanfa_sapp/static/' + "img/" + 'random_noise')
        need_path = self.save_path[0].split('/')[0] + '/random_noise/' + self.save_path[0].split('/')[1] + '_random_noise.jpg'
        self.save_img(need_path)
        return need_path, pnsr, ssim, mse

    def gauss_filter(self):
        # 高斯滤波
        img3 = np.array(self.orig_img)
        # img3PIL_eq = ImageOps.equalize(Image.fromarray(img3))
        # img3_eq = np.array(img3PIL_eq)
        img3_n = skimage.util.random_noise(img3)
        # plt.imshow(img3_n)
        img3_gauss = gauss(img3_n, sigma=1)
        # Create a figure
        fig = plt.figure(figsize=(16, 8))

        # Subplot for original image
        a = fig.add_subplot(1, 2, 1)
        imgplot = plt.imshow(img3_n)
        a.set_title('add random noise')

        # Subplot for processed image
        a = fig.add_subplot(1, 2, 2)
        # imgplot = plt.imshow(img3PIL_eq)
        imgplot = plt.imshow(img3_gauss)
        a.set_title('After gauss')
        pnsr, ssim, mse = self.compute_data(img3_n, img3_gauss)

        if not os.path.exists('suanfa_sapp/static/' + "img/" + 'gauss_filter'):
            os.mkdir('suanfa_sapp/static/' + "img/" + 'gauss_filter')
        need_path = self.save_path[0].split('/')[0] + '/gauss_filter/' + self.save_path[0].split('/')[1] + '_gauss_filter.jpg'
        self.save_img(need_path)
        return need_path, pnsr, ssim, mse

    def med_filter(self):
        # 中值滤波
        img3 = np.array(self.orig_img)
        img3_n = skimage.util.random_noise(img3)
        img3_med = med(img3_n, size=3)
        # plt.imshow(img3_n)
        # Create a figure
        fig = plt.figure(figsize=(16, 8))

        # Subplot for original image
        a = fig.add_subplot(1, 2, 1)
        imgplot = plt.imshow(img3_n)
        a.set_title('add random noise')

        # Subplot for processed image
        a = fig.add_subplot(1, 2, 2)
        # imgplot = plt.imshow(img3PIL_eq)
        imgplot = plt.imshow(img3_med)
        a.set_title('After med')
        pnsr, ssim, mse = self.compute_data(img3_n, img3_med)
        if not os.path.exists('suanfa_sapp/static/' + "img/" + 'med_filter'):
            os.mkdir('suanfa_sapp/static/' + "img/" + 'med_filter')
        need_path = self.save_path[0].split('/')[0] + '/med_filter/' + self.save_path[0].split('/')[1] + '_med_filter.jpg'
        self.save_img(need_path)
        return need_path, pnsr, ssim, mse



    def blur(self, func_name):
        # 平滑
        src = cv2.imread(self.image_path)
        src = cv2.cvtColor(src, cv2.COLOR_BGR2RGB)
        src_noise = skimage.util.random_noise(src)
        result = None
        if func_name=='blur':
            result = cv2.blur(src_noise, (5, 5))
        elif func_name=='GaussianBlur':
            result = cv2.GaussianBlur(src, (5, 5), 0)
        elif func_name == 'medianBlur':
            result = cv2.medianBlur(src, 5)
        elif func_name == 'fastNlMeans':
            # 非局部平均去噪 Non-Local Means
            result = cv2.fastNlMeansDenoisingColored(src, None, 10, 10, 7, 21)
        elif func_name == 'bilateral':
            # 双边滤波器
            result = cv2.bilateralFilter(src, 3, 140, 140)
        else:
            result = src
        # Create a figure
        fig = plt.figure(figsize=(16, 8))

        # Subplot for original image
        a = fig.add_subplot(1, 2, 1)
        imgplot = plt.imshow(src_noise)
        a.set_title('Before')

        # Subplot for resized image
        a = fig.add_subplot(1, 2, 2)
        imgplot = plt.imshow(result)
        a.set_title('After')

        pnsr, ssim, mse = self.compute_data(src_noise, result)
        if not os.path.exists('suanfa_sapp/static/' + "img/" + func_name):
            os.mkdir('suanfa_sapp/static/' + "img/" + func_name)
        need_path = self.save_path[0].split('/')[0] + '/' + func_name + '/' + self.save_path[0].split('/')[1] + '' + func_name +'.jpg'
        self.save_img(need_path)
        return need_path, pnsr, ssim, mse




def process_image(request):
    if request.method == 'GET':
        return render(request, 'bak.html')
    else:
        if request.method == 'POST':
            img_path = settings.IMAGE_PATH
            # 'atc_name'：为<select name="atc_name">标签name的值
            data = request.POST.get('select_name')
            # print("data:", data)
            # print("img_path_process:", img_path)
            image_data = models.Dback.objects.last()
            print('image_data:{}'.format(image_data.image))

            PI = ProcessImage(str(image_data.image))

            if data == '等比缩放':
                need_path = PI.dengbisuofang()
                return render(request, 'bak.html', {'need_path': need_path})
            elif data == '添加椒盐噪声':
                need_path, pnsr, ssim, mse = PI.salt_pepper_noise()
                return render(request, 'bak.html', {'need_path': need_path, 'pnsr':pnsr, 'ssim':ssim, 'mse':mse  })
            elif data == '添加随机噪声':
                need_path, pnsr, ssim, mse = PI.random_noise()
                return render(request, 'bak.html', {'need_path': need_path, 'pnsr':pnsr, 'ssim':ssim, 'mse':mse  })
            elif data == '高斯滤波器':
                need_path, pnsr, ssim, mse = PI.gauss_filter()
                return render(request, 'bak.html', {'need_path': need_path, 'pnsr':pnsr, 'ssim':ssim, 'mse':mse  })
            elif data == '中值滤波':
                need_path, pnsr, ssim, mse = PI.med_filter()
                return render(request, 'bak.html', {'need_path': need_path, 'pnsr':pnsr, 'ssim':ssim, 'mse':mse  })
            elif data == 'blur':
                need_path, pnsr, ssim, mse = PI.blur('blur')
                return render(request, 'bak.html', {'need_path': need_path, 'pnsr':pnsr, 'ssim':ssim, 'mse':mse  })
            elif data == 'GaussianBlur':
                need_path, pnsr, ssim, mse = PI.blur('GaussianBlur')
                return render(request, 'bak.html', {'need_path': need_path, 'pnsr':pnsr, 'ssim':ssim, 'mse':mse  })
            elif data == 'medianBlur':
                need_path, pnsr, ssim, mse = PI.blur('medianBlur')
                return render(request, 'bak.html', {'need_path': need_path, 'pnsr':pnsr, 'ssim':ssim, 'mse':mse  })
            elif data == 'fastNlMeans':
                need_path, pnsr, ssim, mse = PI.blur('fastNlMeans')
                return render(request, 'bak.html', {'need_path': need_path, 'pnsr':pnsr, 'ssim':ssim, 'mse':mse  })
            elif data == 'bilateral':
                need_path, pnsr, ssim, mse = PI.blur('bilateral')
                return render(request, 'bak.html', {'need_path': need_path, 'pnsr':pnsr, 'ssim':ssim, 'mse':mse  })
            # need_path = '../static/images/' + save_path.split('/')[-1]
            #     return render(request, 'bak.html', {'need_path': need_path})

# def process_image(request):
#
#     if request.method == 'GET':
#         return render(request, 'bak.html')
#     else:
#         if request.method == 'POST':
#             img_path = settings.IMAGE_PATH
#             # 'atc_name'：为<select name="atc_name">标签name的值
#             data = request.POST.get('select_name')
#             print("data:", data)
#             print("img_path_process:",img_path)
#             image_data = models.Dback.objects.last()
#             print('image_data{}, type(image_data):{}'.format(image_data.image, type(image_data)))
#
#             if img_path=='':
#                 msg = '提示：请重新上传图片'
#                 return render(request, 'index.html',{'msg':msg})
#             orig_img = Image.open(img_path)
#             print("orig_img:", orig_img)
#             current_time = time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
#             save_path = 'suanfa_sapp/static/images/' + current_time + '.jpg'
#
#             if data=='等比缩放':
#                 # 等比缩放800 × 800
#                 orig_height, orig_width = orig_img.size
#                 print('Original size:', orig_height, 'x', orig_width)
#                 target_size = (800, 800)
#                 scaled_img = orig_img.copy()
#                 scaled_img.thumbnail(target_size, Image.ANTIALIAS)
#                 scaled_height, scaled_width = scaled_img.size
#                 print('Scaled size:', scaled_height, 'x', scaled_width)
#                 # scaled_img.save(save_path)
#                 new_img = Image.new("RGB", (orig_height, orig_width), (255, 255, 255))
#
#                 # 将缩放的图像放置在白色背景上
#                 new_img.paste(scaled_img, (
#                 int((target_size[0] - scaled_img.size[0]) / 2), int((target_size[1] - scaled_img.size[1]) / 2)))
#                 new_height, new_width = new_img.size
#                 print('New size:', new_height, 'x', new_width)
#
#                 # 显示原来的和缩放后的图像
#                 # Create a figure
#                 fig = plt.figure(figsize=(12, 12))
#
#                 # Subplot for original image
#                 a = fig.add_subplot(2, 2, 1)
#                 imgplot = plt.imshow(orig_img)
#                 a.set_title('Original')
#
#                 # Subplot for scaled image
#                 a = fig.add_subplot(2, 2, 2)
#                 imgplot = plt.imshow(scaled_img)
#                 a.set_title('Scaled to 800×800')
#
#                 # Subplot for resized image
#                 a = fig.add_subplot(2, 2, 3)
#                 imgplot = plt.imshow(new_img)
#                 a.set_title('Resized')
#
#                 plt.savefig(save_path)
#                 plt.cla()
#                 plt.close("all")
#
#             elif data=='直方图均衡':
#                 # 梯度直方图
#                 img3 = np.array(orig_img)
#                 img3PIL_eq = ImageOps.equalize(Image.fromarray(img3))
#                 # Create a figure
#                 fig = plt.figure(figsize=(16, 8))
#
#                 # Subplot for original image
#                 a = fig.add_subplot(2, 2, 1)
#                 imgplot = plt.imshow(img3)
#                 a.set_title('Before')
#
#                 # Subplot for processed image
#                 a = fig.add_subplot(2, 2, 2)
#                 # imgplot = plt.imshow(img3PIL_eq)
#                 imgplot = plt.imshow(img3PIL_eq)
#                 a.set_title('After ')
#
#                 img3_eq = np.array(img3PIL_eq)
#
#                 a = fig.add_subplot(2, 2, 3)
#                 imgplot = plt.hist(img3.ravel())
#                 a.set_title('Histogram')
#
#                 a = fig.add_subplot(2, 2, 4)
#                 imgplot = plt.hist(img3_eq.ravel())
#                 a.set_title('After Histogram')
#                 plt.savefig(save_path)
#                 plt.cla()
#                 plt.close("all")
#
#             elif data=='添加随机噪声':
#                 # 随机噪声
#                 img3 = np.array(orig_img)
#                 # img3PIL_eq = ImageOps.equalize(Image.fromarray(img3))
#                 # img3_eq = np.array(img3PIL_eq)
#                 img3_n = skimage.util.random_noise(img3)
#                 # Create a figure
#                 fig = plt.figure(figsize=(16, 8))
#
#                 # Subplot for original image
#                 a = fig.add_subplot(1, 2, 1)
#                 imgplot = plt.imshow(img3)
#                 a.set_title('Before')
#
#                 # Subplot for processed image
#                 a = fig.add_subplot(1, 2, 2)
#                 # imgplot = plt.imshow(img3PIL_eq)
#                 imgplot = plt.imshow(img3_n)
#                 a.set_title('After')
#
#                 plt.savefig(save_path)
#                 plt.cla()
#                 plt.close("all")
#
#             elif data=='高斯滤波器':
#                 # 高斯滤波
#                 img3 = np.array(orig_img)
#                 # img3PIL_eq = ImageOps.equalize(Image.fromarray(img3))
#                 # img3_eq = np.array(img3PIL_eq)
#                 img3_n = skimage.util.random_noise(img3)
#                 # plt.imshow(img3_n)
#                 img3_gauss = gauss(img3_n, sigma=1)
#                 # Create a figure
#                 fig = plt.figure(figsize=(16, 8))
#
#                 # Subplot for original image
#                 a = fig.add_subplot(1, 2, 1)
#                 imgplot = plt.imshow(img3_n)
#                 a.set_title('add random noise')
#
#                 # Subplot for processed image
#                 a = fig.add_subplot(1, 2, 2)
#                 # imgplot = plt.imshow(img3PIL_eq)
#                 imgplot = plt.imshow(img3_gauss)
#                 a.set_title('After gauss')
#                 plt.savefig(save_path)
#                 plt.cla()
#                 plt.close("all")
#
#             elif data=='中值滤波':
#                 # 中值滤波
#                 img3 = np.array(orig_img)
#
#                 img3_n = skimage.util.random_noise(img3)
#                 img3_med = med(img3_n, size=3)
#                 # plt.imshow(img3_n)
#                 # Create a figure
#                 fig = plt.figure(figsize=(16, 8))
#
#                 # Subplot for original image
#                 a = fig.add_subplot(1, 2, 1)
#                 imgplot = plt.imshow(img3_n)
#                 a.set_title('add random noise')
#
#                 # Subplot for processed image
#                 a = fig.add_subplot(1, 2, 2)
#                 # imgplot = plt.imshow(img3PIL_eq)
#                 imgplot = plt.imshow(img3_med)
#                 a.set_title('After med')
#                 plt.savefig(save_path)
#                 plt.cla()
#                 plt.close("all")
#
#             elif data=='扩展':
#                 return render(request, 'download.html')
#             # ../ static / images / 2021_03_17_22_42_16.j
#             # pg
#             need_path = '../static/images/' + save_path.split('/')[-1]
#             return render(request, 'bak.html',{'save_path':need_path})
